// __PUBLIC__/js/page/cms/article/addcontent
require(['../../common'], function() {
  require(['article.addcontent'])
})

define('article.addcontent', [
  'jquery',
  'css!ke/themes/default/default.css',
  'ke/kindeditor',
  'jqp/validate',
  'css!jqp/nouislider.css',
  'jqp/nouislider',
  'css!ztree/ztree.css',
  'ztree/ztree'
], function($) {
  'use strict';

  var $form = $('#J_form'),
      $editor = $('#editor_id'),
      editor,
      eyeHeight = (function(){
        var winHeight = $(window).height();
        if(winHeight > 620){
            return 600;
        }else{
            return winHeight - 20;
        }
      })();
  if ($editor.length) {
    editor = KindEditor.create($editor[0], {
      width: '70%',
      height: '300px',
      allowFileManager: true,
      uploadJson: APP + "?app=cms&m=Cate&a=uploadPic",
      fileManagerJson: APP + "?app=cms&m=Cate&a=getServerPic",
      fullscreenShortcut: true, //ESC快捷键控制编辑器全屏
      langType: 'zh_CN',
      resizeType: 2,
      allowPreviewEmoticons: false,
      allowImageUpload: false,
      items: [
        'source', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
        '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
        '|', 'emoticons', 'image', 'multiimage', 'flash', 'media', 'insertfile',
        'link', 'unlink', '|', 'fullscreen', '|', 'undo', 'redo'
      ]
    })
    KindEditor('#image').click(function() {
      editor.loadPlugin('image', function() {
        editor.plugin.imageDialog({
          hiddenSizeAlignTitle: false,
          imageUrl: KindEditor('#imageurl').val(),
          clickFn: function(url, title, width, height, border, align) {
            KindEditor('#imageurl').val(url);
            $('#showimage').attr('imgurl', url);
            editor.hideDialog();
          }
        });
      });
    });
    KindEditor('#bigimage').click(function() {
      editor.loadPlugin('image', function() {
        editor.plugin.imageDialog({
          hiddenSizeAlignTitle: false,
          imageUrl: KindEditor('#big_imageurl').val(),
          clickFn: function(url, title, width, height, border, align) {
            KindEditor('#big_imageurl').val(url);
            $('#showbigimage').attr('imgurl', url);
            editor.hideDialog();
          }
        });
      });
    });
    KindEditor('#file_upload').click(function() {
      editor.loadPlugin('insertfile', function() {
        editor.plugin.fileDialog({
          fileUrl: KindEditor('#fileurl').val(),
          clickFn: function(url, title) {
            KindEditor('#fileurl').val(url);
            editor.hideDialog();
          }
        });
      });
    });

    KindEditor('#select_related_articles').click(function() {
      var url = $(this).data('url')
      var dialog = KindEditor.dialog({
        width: '800px',
        height: eyeHeight,
        title: '选择相关文章',
        body: '<iframe id="content-frame" name="contentFrame" frameborder="0" src="' + url + '"></iframe>',
        closeBtn: {
          name: '关闭',
          click: function(e) {
            dialog.remove();
          }
        },
        yesBtn: {
          name: '确定',
          click: function(e) {
            var arr = []
            var oldval = []
            var i = 0
            var html = ""
            $('#content-frame').contents().find('tbody').find(':checked').each(function() {
              arr.push($(this).closest('tr').data('value'))
            })

            $("input[name^='related_articles']").each(
              function() {
                oldval[i] = $(this).val();
                i++;
              }
            )

            for (var i = 0; i < arr.length; i++) {
              var val = arr[i].split("_yl_");
              var url = APP + "?app=cms&m=Article&a=preview&id=" + val[0];
              if ($.inArray(arr[i], oldval) > -1) {
                continue;
              }
              html += '<p id="related_articles_' + val[0] + '">';
              html += '<input type="hidden" name="related_articles[]" value="' + arr[i] + '"/>';
              html += '<a href="' + url + '"  target="_blank" class="ico_top">' + val[1] + '</a>&nbsp;&nbsp; ';
              html += '<a href="javascript:;" id="J_relatedRemove" data-aid="' + val[0] + '" class="ico_top" >取消</a><br/></p>';
            }
            $("#related_articles_div").append(html);
            dialog.remove();
          }
        },
        noBtn: {
          name: '取消',
          click: function(e) {
            dialog.remove();
          }
        }
      });
    })

    KindEditor('#select_block_articles').click(function() {
      selBlock()
    })
  }

  $(document)
    .on('click', '#J_stitle', function(e) {
      var isCheck = $(this).prop('checked');
      if (isCheck) {
        $('.J_stitle').show()
      } else {
        $('.J_stitle').hide()
      }
    })
    .on('click', '#J_smore', function(e) {
      var isCheck = $(this).prop('checked');
      if (isCheck) {
        $('.J_smore').show()
      } else {
        $('.J_smore').hide()
      }
    })
    .on('click', '#J_suopic', function(e) {
      e.preventDefault()
      getThumb()
    })
    .on('click', '#J_relatedRemove', function(e) {
      e.preventDefault()
      $('#related_articles_' + $(this).data('aid')).remove()
    })
    .on('click', '#J_blockRemove', function(e) {
      e.preventDefault()

      var aid = $(this).data('aid'),
        id = $('#J_id').val()

        // 取消的同时删除对应区块

        $.post(APP + '?app=cms&m=Article&a=delBlockByContentID', {
          id: aid,
          contentID: id
        }).done(function(res) {
          if (res === '1') {
            $('#block_articles_' + aid).remove()
          }
        })
    })
    .on('click', '#J_detection', function(e) {
      e.preventDefault()
      detection()
    })
    .ready(function() {
      $('.staff').bind('focus keyup input paste', function() {
        countNumber(this, '.word_count')
      })
      $('.J_subtitle').bind('focus keyup input paste', function() {
        countNumber(this, '.J_sword')
      })
      previewImage('#imageurl')
      previewImage('#big_imageurl')
      countNumber('.staff', '.word_count')
      countNumber('.J_subtitle', '.J_sword')
    })
    .keydown(function(e) {
      if (e.keyCode === 83 && e.ctrlKey) {
        e.preventDefault()
        $form.submit()
      }
    })

  function countNumber(el, b) {
    var length = $(el).val().length
    $(b).html(length)
  }

  function previewImage(el) {
    $(el).mouseover(function(e) {
      var imageurl = $(this).val()
      if (imageurl) {
        $('#detailImg').attr('src', imageurl)
        $('#details').css('top', e.pageY).css('left', e.pageX).css('display', 'block')
      }
    }).mouseout(function() {
      $('#details').hide()
    })
  }

  function getThumb() {
    var content = editor.html()
    var imgs = content.match(/<img\s+[^>]*src\s*=\s*(["\']?)([^>"\']+)\1[^>]*[\/]?>/im);
    if (imgs) {
      $('#imageurl').val(imgs[2])
    }
  }

  //关键词密度检测

  function detection() {
    var keywords = $("input[name='keywords']").val()
    var content = editor.html().replace(/<\/?[^>]+>/gi, '')

    if (keywords === "" || content === "") {
      alert('文章内容或关键字不能为空');
      return false;
    }

    $("tr[name='detection']").remove()

    var kwds = keywords.split(","),
      percent = 0,
      num = 0,
      html = ''

    for (var i = 0, len = kwds.length; i < len; i++) {
      num = content.split(kwds[i]).length - 1

      html += "<tr name='detection'><td>" + kwds[i] + "</td>"
      html += "<td>" + num + "</td>"

      percent = Math.round(kwds[i].length * num / content.length * 1000) / 10.0

      if (percent < 2.0 || percent > 8.0) {
        html += "<td><font color='red'>" + percent + "%" + "<font></td></tr>"
      } else {
        html += "<td>" + percent + "%" + "</td></tr>"
      }
    }
    $("#detection_result").append(html)
    $("#detection_result").show()
  }

  function selBlock() {
    var dialog = KindEditor.dialog({
      width: '400px',
      height: eyeHeight,
      title: '选择区块',
      body: '<div id="dialoghtml" style="margin:10px;overflow:auto;">' + '<div class="zTreeDemoBackground left"  style="height:100%;width:181px;overflow:auto;">' + '<ul id="dialog_treeDemo" class="ztree" style="margin-top:10px;"></ul>' + '</div></div>',
      closeBtn: {
        name: '关闭',
        click: function(e) {
          e.preventDefault()
          dialog.remove();
        }
      },
      yesBtn: {
        name: '确定',
        click: function(e) {
          e.preventDefault()
          var treeObj = $.fn.zTree.getZTreeObj("dialog_treeDemo"),
            nodes = treeObj.getCheckedNodes(),
            html = ''

          for (var i = 0; i < nodes.length; i++) {
            if (nodes[i]['isParent'] === false) {
              html += '<p id="block_articles_' + nodes[i]['id'] + '">';
              html += '<input type="hidden" name="block_articles[]" value="' + nodes[i]['id'] + '"/>';
              html += '<label>' + nodes[i]['name'] + ' </label>';
              html += '<a href="javascript:;" id="J_blockRemove" data-aid="' + nodes[i]['id'] + '" class="ico_top" >取消</a><br/></p>';
            }
          }
          $('#block_articles_div').html(html)
          dialog.remove();
        }
      },
      noBtn: {
        name: '取消',
        click: function(e) {
          e.preventDefault()
          dialog.remove();
        }
      }
    });
    var setting = {
      check: {
        enable: true
      },
      data: {
        simpleData: {
          enable: true
        }
      },
    };
    $.ajax({
      async: false,
      cache: false,
      type: 'POST',
      dataType: "json",
      url: APP + '?app=cms&m=Block&a=getBlockInfo', //请求的action路径
      data: {
        id: 1
      },
      success: function(data) { //请求成功后处理函数。
        $.fn.zTree.init($("#dialog_treeDemo"), setting, data['children']);
      }
    });
  }

  var Link = $.noUiSlider.Link
  var $weight = $('#J_weight')
  var weight = parseInt($weight.val(), 10) || 60
  $("#range-slider").noUiSlider({
    start: weight,
    step: 1,
    range: {
      'min': 0,
      'max': 100
    },
    serialization: {
      lower: [
        new Link({
          target: $weight
        })
      ],
      format: {
        decimals: 0
      }
    }
  })


  $form.validate({
    classPlace: '.kv',
    errorPlace: '.kv-error',
    errors: {
      'title': {
        required: '文章标题不能为空'
      }
    }
  })


})